/**查找分页控件 -> 请求下一页 -> 增删元素 -> 加载在页面 */
async function loadNextPage() {
  let [lastNrPage] = [...document.querySelectorAll('.clearfix ul')].slice(-1)
  let url = lastNrPage.querySelector('li a:nth-of-type(4)').href

  const response = await fetch(url)
  const decoder = new TextDecoder('gbk')
  const html = decoder.decode(await response.arrayBuffer())
  let div = document.createElement('div')
  div.innerHTML = html

  let alink = document.createElement('a')
  alink.href = url
  alink.innerText = '本页'
  let pageDom = div.querySelector('.clearfix ul li:nth-of-type(2)')
  if (pageDom) {
    pageDom.insertBefore(alink, pageDom.children[3])
    pageDom.removeChild(pageDom.children[4])
  }

  cleanPage(div)
  addSpace(div)

  let [lastContent] = [...document.querySelectorAll('article')].slice(-1)
  lastContent.parentNode.appendChild(div)
  return {div, url}
}

function getBookLink() {
  const { host, href, origin } = location
  if (href.endsWith('index.html')){
    return href
  }
  let result = href.match(/book\/(\w+)/)
  if (result && result.length) {
    return host + `/xs/${result[1]}/index.html`
  }
}

/**从页面获取书名 */
function getBookName() {
  let el = document.querySelector('.breadcrumb .active')
  return el ? el.innerText : ''
}

/**_addObserver传入targetSelector、chapterTitleSelector*/
function addObserver(dom = document, url = location.href) {
  _addObserver('article', '#h1 h1', dom, url)
}

/**包装cleanPage方法 */
function cleanPage(context = document) {
  $chromePlugin.cleanPage(context, ['header', '#h1 small', '.tac', '.clearfix ul li:nth-of-type(1)', '.clearfix ul li:nth-of-type(2)', 'ins', '.hidden', '.footer', '#google_esf', 'iframe'])
}

/**添加段落之间的间隔， 提升阅读体验 */
function addSpace(context = document) {
  let dom = context.querySelector('#txtContent')
  if (!dom) return
  dom.style.fontSize = '24px'
  let brNodeList = dom.querySelectorAll('br')
  for (let i = 0; i < brNodeList.length; i++) {
    let brNode = brNodeList[i]
    if (i == 0 && $chromePlugin.getNextNodeName(brNode) == 'BR') break
    dom.insertBefore(document.createElement('br'), brNode)
  }
}

$chromePlugin.loadQueueFn.push(cleanPage, addSpace)